/*******************************************************************************
*  file    : saveloadobjectjson.cpp
*  created : 07.08.2014
*  author  : Slyshyk Oleksiy (alexSlyshyk@gmail.com)
*******************************************************************************/

#include "saveloadobjectjson.hpp"
#include <dataobject.hpp>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonArray>
#include <QFile>

SaveLoadObjectJson::SaveLoadObjectJson(QObject *parent) :
    QObject(parent)
{
}

QString SaveLoadObjectJson::name() const
{
    return QString("object_json");
}

QString SaveLoadObjectJson::error() const
{
    return lastError_;
}

QStringList SaveLoadObjectJson::formats() const
{
    QStringList res;
    res << "json";
    return res;
}

QString SaveLoadObjectJson::fileFilter() const
{
    return QString("json (*.json)");
}

bool SaveLoadObjectJson::saveObjectToFile(const QString &fileName, QObject *object)
{
    DataObject* data_object = dynamic_cast<DataObject*>(object);

    if( !data_object)
        return false;

    QFile file;
    file.setFileName(fileName);
    if(file.open(QIODevice::WriteOnly |QIODevice::Truncate | QIODevice::Text))
        {
            file.write(data_object->toJsonDocument().toJson(QJsonDocument::Compact));
            file.close();
        }

    return true;
}

QObject *SaveLoadObjectJson::loadObjectFromFile(const QString &fileName)
{
    DataObject* data_object = new DataObject;

    QFile file(fileName);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QJsonParseError error;
            QJsonDocument document(QJsonDocument::fromJson(file.readAll(),&error));
            file.close();
            data_object->updateFromJson(document);
        }

    return data_object;
}
